﻿using System.Linq;
using System.Web.Mvc;
using BLL.Services.Authors;
using BLL.Services.Books;
using Web.Infrastructure;
using Web.Models;

namespace Web.Controllers
{
    public partial class AuthorsController : FrontendController
    {
        private readonly IAuthorsService AuthorsService;

        private readonly IBookService BookService;

        public AuthorsController(
            IAuthorsService authorsService,
            IBookService bookService)
        {
            AuthorsService = authorsService;
            BookService = bookService;
        }

        [HttpGet]
        public virtual ActionResult ListingTemplate(string letter)
        {
            return BackBoneView(MVC.Authors.Views.Listing);
        }

        public virtual ActionResult Listing(string letter)
        {
            var model = new AuthorListModel();
            if (!string.IsNullOrEmpty(letter))
            {
                model.Authors =
                    AuthorsService.GetAuthorsByLetter(letter).Select(x => new AuthorListModel.AuthorModel(x)).
                        OrderBy(x => x.LastName);
            }
            return BackBoneJson(model);
        }

        [HttpGet]
        public virtual ActionResult ShowTemplate()
        {
            return BackBoneView(MVC.Authors.Views.Show);
        }

        public virtual ActionResult Show(int? authorId)
        {
            var model = new AuthorBooksListModel();
            if (authorId.HasValue)
            {
                model.AuthorsBooks = 
                    BookService.GetBooksByAuthor(authorId.Value).Select(x => new AuthorBooksListModel.AuthorBookModel(x)).
                        OrderBy(x => x.Name);
                return BackBoneJson(model);
            }
            return BackBoneJson(model);
        }

    }
}